import React from 'react';
import { inject, observer } from 'mobx-react';
import { Modal, Button, Row, Col, Tooltip } from 'antd';
import * as mobx from 'mobx';
import { WeaLocaleProvider, WeaDialog, WeaSelect } from 'ecCom';
import isEmpty from 'lodash/isEmpty';
import DirectionTable from './DirectionTable';
import Remark from './Remark';
import UsualDirectionDialog from './dialog/UsualDirectionDialog';
import SelectDirectionDialog from './dialog/SelectDirectionDialog';

import * as dialogTypes from '../../constants/OdocCompsDialogType';
import * as Util from '../../util/odocTransferUtil';

import './style/index';

const getLabel = WeaLocaleProvider.getLabel;

@inject('odocRequestStore', 'odocCompsStore')
@observer
class Main extends React.Component {
  constructor(props) {
    super(props);

    this.openDirectionDialog = this.openDirectionDialog.bind(this);
    this.openUsualDirectionDialog = this.openUsualDirectionDialog.bind(this);
    this.closeDialog = this.closeDialog.bind(this);
    this.doSubmit = this.doSubmit.bind(this);
    this.saveDirection = this.saveDirection.bind(this);
    this.setSelectDirection = this.setSelectDirection.bind(this);
  }

  componentWillMount() {
    this.loadData();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.visible != nextProps.visible && nextProps.visible) {
      this.loadData();
    }
  }


  loadData() {
    const { dataId, odocCompsStore, odocRequestStore } = this.props;
    let { requestParam = {} } = odocCompsStore;
    requestParam = mobx.toJS(requestParam);
    delete requestParam.markInfo;
    const params = { dataId, ...requestParam };

    // 加载数据
    odocRequestStore.loadData(params);
  }

  closeDialog() {
    const { onClose, odocRequestStore } = this.props;
    onClose && onClose();

    odocRequestStore.resetStore();
  }

  /**
   * 流程流转
   */
  doSubmit() {
    const { odocCompsStore, odocRequestStore, onSuccess } = this.props;
    let { requestParam } = odocCompsStore;
    requestParam = mobx.toJS(requestParam);
    const { workflowid } = requestParam;
    delete requestParam.markInfo;

    let { btnforbiden, isend, nodeOperatorMap = {} } = odocRequestStore;
    const nextDirections = odocRequestStore.getNextDirections(); // 存储选中的节点
    nodeOperatorMap = mobx.toJS(nodeOperatorMap); // 存储每个节点设置的操作者

    if (btnforbiden) { // 重复提交
      return;
    }

    const userNames = [];
    const userIdset = new Set();
    const nodeIdSet = new Set();
    let hasArchive = false; // 选择的节点是否包含归档节点
    let archiveNodeName = '';

    const cssText = {
      margin: '0 5px',
      'font-weight': 'bold',
      color: '#2db7f5',
    };

    if (isEmpty(nodeOperatorMap) || nextDirections.length <= 0) {
      Util.showGlobalError(getLabel(523407, '请至少设置1个环节的操作人员！'));
      return;
    }
    // 必填验证
    const checkFail = nextDirections.some((item) => {
      const { userList = [], nodeid: nid, nodename: nname, nodetype, selected = false } = item;
      if (selected && userList.length > 0) {
        nodeIdSet.add(nid);

        if (nodetype == 3) { // 归档节点
          hasArchive = true;
          archiveNodeName = nname;
        }

        userList.forEach((item2) => {
          const { id: uid, name: uname, lastname: uname2 } = item2;

          if (!userIdset.has(uid)) {
            userIdset.add(uid);
            userNames.push(uname || uname2);
          }
        });
      }

      if (selected && userList.length <= 0) {
        let errormsg = getLabel(523409, '请添加流转环节$nodename的操作人员');
        const cssTextstr = 'margin:0 5px;font-weight:bold;color:#2db7f5';
        errormsg = errormsg.replace(/\$nodename/ig, `<span style="${cssTextstr}">${nname}</span>`);
        // Util.showGlobalError(<span>请添加流转环节<span style={cssText}>{nname}</span>的操作人员</span>, 3);
        Util.showGlobalError(<span dangerouslySetInnerHTML={{ __html: errormsg }} />, 3);
      }

      return selected && userList.length <= 0;
    });

    if (checkFail) {
      return;
    }


    // 说明除了选择归档节点，还选择了其他节点
    if (hasArchive && nodeIdSet.size > 1) {
      const cmsg = [<span style={cssText}>{archiveNodeName}</span>, <span>{getLabel(523408, '是归档环节，不能与其他环节同时流转，请重新选择！')}</span>];
      Util.showGlobalError(cmsg, 3);
      return;
    }

    odocRequestStore.setMember({ workflowid, btnforbiden: true });
    const remark = window.CK_REF.oDocRemark.getEditor().getData();

    // const params = {requestid, workflowid, nodeid, remark};
    const params = { remark, ...requestParam };

    // 回调方法
    const callback = (data) => {
      const { success = 0, msg = '' } = data;

      if (success == 1) { // 提交成功
        Util.showGlobalMessage(msg, 3);

        odocRequestStore.resetStore();
        window.setTimeout(() => {
          onSuccess && onSuccess(isend, data);
        }, 100);
      } else if (success == 2) { // 批量提交时使用，暂不支持
        odocRequestStore.resetStore();
        window.setTimeout(() => {
          onSuccess && onSuccess(isend, data);
        }, 100);
      } else {
        Util.showGlobalError(msg, 3);
        odocRequestStore.setMember({ btnforbiden: false });
      }
    };

    let confirmMsg0 = getLabel(513015, '确认将文件发送给$username处理？');

    // 存在归档节点
    if (hasArchive) {
      confirmMsg0 = getLabel(519033, '确认将文件送阅给$username，并将流程归档？');
    }

    const confirmMsg = this.transformConfirmMsg(confirmMsg0, userNames, cssText);

    Modal.confirm({
      title: getLabel(22575, '系统提醒消息'),
      content: confirmMsg,
      onOk: () => {
        odocRequestStore.flowNext(params, callback);
      },
      onCancel: () => {
        odocRequestStore.setMember({ btnforbiden: false });
      },
    });
  }

  transformConfirmMsg(cfmMsg, userNames, cssText) {
    const fontCss = { 'font-size': '18px' };

    let nameStr = '';
    let allNames = '';
    if (userNames.length > 10) {
      allNames = userNames.join(', ');
      nameStr = `${userNames.slice(0, 10).join(', ')}...`;
    } else {
      nameStr = userNames.join(', ');
    }

    const findex = cfmMsg.indexOf('$username');
    const lindex = findex + 9; // 9是$username这几个字符的长度

    const fmsg = cfmMsg.substring(0, findex);
    const lmsg = cfmMsg.substring(lindex);

    let showNames = '';
    if (allNames.length > 0) {
      const titleText = (
        <span style={fontCss}>
          {allNames}
        </span>
      );
      showNames = (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@ksqmn8`} placement="rightTop" title={titleText}>
          <span style={cssText}>{nameStr}</span>
        </Tooltip>
      );
    } else {
      showNames = <span style={cssText}>{nameStr}</span>;
    }

    const confirmMsg = (
      <span style={fontCss}>
        {fmsg}
        {showNames}
        {lmsg}
      </span>
    );

    return confirmMsg;
  }

  getTopButtons() {
    const buttons = [];
    buttons.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5s3njg@select`} onClick={this.openDirectionDialog}>{getLabel(512917, '选择常用去向')}</Button>,
    );
    buttons.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@brieln@setting`} onClick={this.openUsualDirectionDialog}>{getLabel(512918, '设为常用去向')}</Button>,
    );
    return buttons;
  }

  /**
   * 保存常用去向
   */
  saveDirection() {
    const { odocRequestStore, odocCompsStore } = this.props;
    let { requestParam = {} } = odocCompsStore;
    requestParam = mobx.toJS(requestParam);
    delete requestParam.markInfo;
    // 回调方法
    let callback = () => {
      Util.showGlobalMessage(getLabel(512221, '保存成功!'));
      odocRequestStore.controlDialogVisible(dialogTypes.USUAL_DIRECTION_DIALOG, false);
    };

    odocRequestStore.saveDirection({ ...requestParam }, callback);
  }

  /**
   * 设为常用去向
   */
  openUsualDirectionDialog() {
    const { odocRequestStore } = this.props;

    let { nodeOperatorMap = {} } = odocRequestStore;
    const nextDirections = odocRequestStore.getNextDirections(); // 存储选中的节点
    nodeOperatorMap = mobx.toJS(nodeOperatorMap); // 存储每个节点设置的操作者

    if (isEmpty(nodeOperatorMap) || nextDirections.length <= 0) {
      Util.showGlobalError(getLabel(523407, '请至少设置1个环节的操作人员！'));
      return;
    }

    odocRequestStore.controlDialogVisible(dialogTypes.USUAL_DIRECTION_DIALOG, true);
  }

  // 从常用去向导入后，根据选择的去向加载数据
  setSelectDirection(data) {
    const { randomFieldId: dataId } = data;
    const { odocCompsStore, odocRequestStore } = this.props;
    let { requestParam = {} } = odocCompsStore;
    requestParam = mobx.toJS(requestParam);
    delete requestParam.markInfo;
    const params = { dataId, ...requestParam };

    // 加载数据
    odocRequestStore.importData(params, () => {
      Util.showGlobalMessage(getLabel(30700, '操作成功！'));
    });
  }

  /**
   * 选择常用去向
   */
  openDirectionDialog() {
    const { odocRequestStore } = this.props;
    odocRequestStore.controlDialogVisible(dialogTypes.SELECT_DIRECTION_DIALOG, true);
  }

  render() {
    const { visible, title, workflowid, odocRequestStore } = this.props;
    const { dialogVisible, isend } = odocRequestStore;
    const style = { width: 800, height: 600 };
    const onCancel = this.closeDialog;
    const buttons = [];
    const layout = jQuery('.wf-req')[0];
    const scalable = true;

    buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cro4qy@ok`} onClick={this.doSubmit} type="primary">{getLabel(501196, '确定')}</Button>);
    buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s6xk3v@cancel`} onClick={this.closeDialog}>{getLabel(31129, '取消')}</Button>);

    const dialogParams = { title, style, visible, onCancel, buttons, layout, scalable };

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@jelcy3`} {...dialogParams}>
        <div className="odoc-workflow-transfer">
          <div className="direction-top">
            <div className="title">
              {getLabel(521993, '请选择流转操作者')}
              <div className="top-buttons">
                {this.getTopButtons()}
              </div>
            </div>

            <div className="direction-table">
              <DirectionTable ecId={`${this && this.props && this.props.ecId || ''}_DirectionTable@9ligxy`} workflowid={workflowid} />
            </div>
          </div>

          <div className="direction-bottom">
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@oju9qp`}>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ci5z08`} span={24}>
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@3qbst3`}
                  options={[{ key: '1', showname: getLabel(507363, '结束本人处理') }]}
                  detailtype={2}
                  value={isend}
                  onChange={(v) => {
                    odocRequestStore.setMember({ isend: v });
                  }}
                />
              </Col>
            </Row>

            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2q66j4`}>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@0u97sf`} span={24}>
                <Remark ecId={`${this && this.props && this.props.ecId || ''}_Remark@1fupdy`} visible={visible} />
              </Col>
            </Row>
          </div>
        </div>

        {
          dialogVisible.has(dialogTypes.USUAL_DIRECTION_DIALOG) &&
          <UsualDirectionDialog ecId={`${this && this.props && this.props.ecId || ''}_UsualDirectionDialog@3owfgi`} onSave={this.saveDirection} />
        }

        {
          dialogVisible.has(dialogTypes.SELECT_DIRECTION_DIALOG) &&
          <SelectDirectionDialog ecId={`${this && this.props && this.props.ecId || ''}_SelectDirectionDialog@pqjpn6`}
            workflowid={workflowid}
            visible={dialogVisible.get(dialogTypes.SELECT_DIRECTION_DIALOG)}
            onSelect={this.setSelectDirection}
          />
        }
      </WeaDialog>
    );
  }
}

export default Main;
